package com.julyup.quartz.controller;

import com.julyup.quartz.job.HelloJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: zhenzhong.wang@honeywell.com
 * @Date: 2019/3/20 11:57 AM
 */
@RestController
public class CreateJobController {

  @Autowired
  Scheduler scheduler;

  @PostMapping("/api/create")
  public String create() throws SchedulerException {
    scheduler.start();
    JobDetail helloJob = JobBuilder.newJob(HelloJob.class).withIdentity("helloJob").build();

    CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule("0/2 * * * * ? ");

    Trigger helloTrigger = TriggerBuilder.newTrigger().forJob(helloJob).withIdentity("helloTrigger").usingJobData("name", "lalala")
        .withSchedule(cronSchedule).build();
    scheduler.scheduleJob(helloJob, helloTrigger);
    return "OK";
  }

  @PostMapping("/api/delete")
  public String deleteJob(@RequestParam("jobName") String jobName) throws SchedulerException {
    scheduler.deleteJob(JobKey.jobKey(jobName));
    return "OK";
  }

  @PostMapping("/api/stop")
  public String stopJob(@RequestParam("jobName") String jobName) throws SchedulerException {
    scheduler.pauseJob(JobKey.jobKey(jobName));
    return "OK";
  }

  @PostMapping("/api/simple")
  public String createSimple() throws SchedulerException {
    scheduler.start();
    JobDetail helloJob = JobBuilder.newJob(HelloJob.class).withIdentity("helloJob2").build();


    SimpleScheduleBuilder simpleScheduleBuilder = SimpleScheduleBuilder.repeatSecondlyForever(3);
    Trigger helloTrigger = TriggerBuilder.newTrigger().forJob(helloJob).withIdentity("helloTrigger2").usingJobData("name", "lalala")
        .withSchedule(simpleScheduleBuilder).build();

//    TriggerBuilder<Trigger> triggerTriggerBuilder = TriggerBuilder.newTrigger().forJob(helloJob).startAt(new Date());

    scheduler.scheduleJob(helloJob, helloTrigger);
    return "OK";
  }

  @PostMapping("/api/start")
  public String startJob(@RequestParam("jobName") String jobName) throws SchedulerException {
    scheduler.resumeJob(JobKey.jobKey(jobName));
    return "OK";
  }
}
